package com.xiaoxu.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.bbs.common.ReturnResults;
import com.xiaoxu.bbs.entity.Topic;
import com.xiaoxu.bbs.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/topic")
public class TopicController {
    @Autowired
    private TopicService topicService;

    @GetMapping("/list/{BoardId}")
    public ReturnResults getTopics(@PathVariable Long BoardId, Integer page, Integer pageSize, HttpSession session){
        session.setAttribute("boardId",BoardId);
        LambdaQueryWrapper<Topic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BoardId != null,Topic::getBoardId,BoardId);
        wrapper.orderByAsc(Topic::getUpdateTime);
        if (pageSize != null && page != null) {
            Page<Topic> pageInfo = new Page<>(page,pageSize);
            topicService.page(pageInfo,wrapper);
            return ReturnResults.success(pageInfo);
        }
        List<Topic> topics = topicService.list(wrapper);
        if (topics != null) {
            return ReturnResults.success(topics);
        }
        return ReturnResults.error("业务出异常了，请向工作人员反馈!");
    }

    @GetMapping("/count/{BoardId}")
    public ReturnResults getTopicCount(@PathVariable Long BoardId){
        LambdaQueryWrapper<Topic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BoardId != null,Topic::getBoardId,BoardId);
        List<Topic> list = topicService.list(wrapper);
        if (list != null) {
            return ReturnResults.success(list.size());
        }
        return ReturnResults.error("业务出异常了，请向工作人员反馈!");
    }

    @PostMapping("/add")
    public ReturnResults saveTopic(@RequestBody Topic topic){
        if (topic != null) {
            topicService.save(topic);
            return ReturnResults.success("添加成功!");
        }
        return ReturnResults.error("添加失败");
    }

    @GetMapping("/{topicId}")
    public ReturnResults getTopicById(@PathVariable Long topicId){
        if (topicId != null) {
            Topic topic = topicService.getById(topicId);
            return ReturnResults.success(topic);
        }
        return ReturnResults.error("业务出异常了，请向工作人员反馈!");
    }
    @PostMapping("/edit")
    public ReturnResults editTopicById(@RequestBody Topic topic){
        topicService.updateById(topic);
        return ReturnResults.success("更新成功!");
    }
    @GetMapping("/delete/{topicId}")
    public ReturnResults deleteTopic(@PathVariable Long topicId){
        Boolean res = topicService.deleteTopicWithItReplys(topicId);
        if (res){
            return ReturnResults.success("删除成功!");
        }else{
            return ReturnResults.error("删除失败，请联系管理人员!");
        }
    }
}
